module SyllableCounter
  class Rules

    def call(word)
      parsed_word = clean_input(word)
      parsed_word = clean_input(word)
      parsed_word = delete_trailing_e(parsed_word)
      parsed_word = delete_past_ed(parsed_word)
      parsed_word = combine_consecutive_vowels(parsed_word)
      parsed_word = remove_plural_suffix(parsed_word)
      parsed_word
    end

    private

    def delete_trailing_e(word)
      #deletes trailing e if preceded by a vowel+[lr] or [^lr]
      if word =~ /[aeiouy][lr]e$/ || word =~ /[^lr]e$/
        word.sub!(/e$/,"")
      end
      word
    end

    def delete_past_ed(word)
      #removes /ed/ suffix except when preceded by /t/ or /d/

      if word =~ /[^td]ed$/
        word.sub!(/ed$/,"")
      end
      word
    end

    def combine_consecutive_vowels(word)
      #combines consecutive vowels and replpaces with % placeholder

      while word =~ /[aeiouy%][aeiouy%]/
        word.sub!(/[aeiouy%][aeiouy%]/,"%")
      end
      word
    end

    def remove_plural_suffix(word)
      #Final /es/ plural suffix is realized after /s/ /z/ /sh/ /dg/ /ch/ /[aeiou]g/
      if word =~ /[^([z]|[sh]|[dg]|[ch]|[aeiouy][g]|[s])]es$/
        word.sub!(/es$/,"")
      end
      word
    end

    def clean_input(word)
      word.downcase.strip
    end
  end
end
